package models

import (
	"errors"
	"gitee.com/ha666/golibs"
	"strconv"
)

type Userinfo struct {
	UserId      int64  //用户编号
	UserNick    string //用户昵称
	Password    string //密码，暂定HMAC-SHA512算法
	Slat        string //盐值
	Email       string //邮箱地址
	Mobile      int64  //手机号
	LastLoginIP string //最后登录IP地址
	Status      int    //状态，1未激活，2已激活
	LoginTime   int64  //最后登录时间
}

func ExistUserinfo(UserId int64) (bool, error) {
	rows, err := Ha666DBConn.Query("select count(0) Count from userinfo where UserId=?", UserId)
	if err != nil {
		return false, err
	}
	if len(rows) <= 0 {
		return false, nil
	}
	for _, obj := range rows {
		count, err := strconv.Atoi(string(obj["Count"]))
		if err != nil {
			return false, errors.New("parse Count error: " + err.Error())
		}
		return count > 0, nil
	}
	return false, nil
}

func InsertUserinfo(userinfo Userinfo) (int64, error) {
	result, err := Ha666DBConn.Exec("insert into userinfo(UserNick,Password,Slat,Email,Mobile,LastLoginIP,Status,LoginTime) values(?,?,?,?,?,?,?,?)", userinfo.UserNick, userinfo.Password, userinfo.Slat, userinfo.Email, userinfo.Mobile, userinfo.LastLoginIP, userinfo.Status, userinfo.LoginTime)
	if err != nil {
		return -1, err
	}
	return result.LastInsertId()
}

func UpdateUserinfo(userinfo Userinfo) (bool, error) {
	result, err := Ha666DBConn.Exec("update userinfo set UserNick=?, Password=?, Slat=?, Email=?, Mobile=?, LastLoginIP=?, Status=?, LoginTime=? where UserId=?", userinfo.UserNick, userinfo.Password, userinfo.Slat, userinfo.Email, userinfo.Mobile, userinfo.LastLoginIP, userinfo.Status, userinfo.LoginTime, userinfo.UserId)
	if err != nil {
		return false, err
	}
	affected, err := result.RowsAffected()
	if err != nil {
		return false, err
	}
	return affected > 0, nil
}

func InsertUpdateUserinfo(userinfo Userinfo) (bool, error) {
	result, err := Ha666DBConn.Exec("insert into userinfo(UserNick,Password,Slat,Email,Mobile,LastLoginIP,Status,LoginTime) values(?,?,?,?,?,?,?,?) ON DUPLICATE KEY UPDATE UserNick=?,Password=?,Slat=?,Email=?,Mobile=?,LastLoginIP=?,Status=?,LoginTime=?", userinfo.UserNick, userinfo.Password, userinfo.Slat, userinfo.Email, userinfo.Mobile, userinfo.LastLoginIP, userinfo.Status, userinfo.LoginTime, userinfo.UserNick, userinfo.Password, userinfo.Slat, userinfo.Email, userinfo.Mobile, userinfo.LastLoginIP, userinfo.Status, userinfo.LoginTime)
	if err != nil {
		return false, err
	}
	affected, err := result.RowsAffected()
	if err != nil {
		return false, err
	}
	return affected > 0, nil
}

func GetUserinfo(UserId int64) (userinfo Userinfo, err error) {
	rows, err := Ha666DBConn.Query("select UserId, UserNick, Password, Slat, Email, Mobile, LastLoginIP, Status, LoginTime from userinfo where UserId=?", UserId)
	if err != nil {
		return userinfo, err
	}
	if len(rows) <= 0 {
		return userinfo, nil
	}
	userinfos, err := _UserinfoRowsToArray(rows)
	if err != nil {
		return userinfo, err
	}
	return userinfos[0], nil
}

// idx_userinfo_email
func GetUserinfoByEmail(Email string) (userinfo Userinfo, err error) {
	rows, err := Ha666DBConn.Query("select UserId, UserNick, Password, Slat, Email, Mobile, LastLoginIP, Status, LoginTime from userinfo where email=?", Email)
	if err != nil {
		return userinfo, err
	}
	if len(rows) <= 0 {
		return userinfo, nil
	}
	userinfos, err := _UserinfoRowsToArray(rows)
	if err != nil {
		return userinfo, err
	}
	return userinfos[0], nil
}

// idx_userinfo_mobile
func GetUserinfoByMobile(Mobile int64) (userinfos []Userinfo, err error) {
	rows, err := Ha666DBConn.Query("select UserId, UserNick, Password, Slat, Email, Mobile, LastLoginIP, Status, LoginTime from userinfo where mobile=?", Mobile)
	if err != nil {
		return userinfos, err
	}
	if len(rows) <= 0 {
		return userinfos, nil
	}
	return _UserinfoRowsToArray(rows)
}

func GetUserinfoRowCount() (count int, err error) {
	rows, err := Ha666DBConn.Query("select count(0) Count from userinfo")
	if err != nil {
		return -1, err
	}
	if len(rows) <= 0 {
		return -1, nil
	}
	for _, obj := range rows {
		count, err := strconv.Atoi(string(obj["Count"]))
		if err != nil {
			return -1, errors.New("parse Count error: " + err.Error())
		}
		return count, nil
	}
	return -1, nil
}

// idx_userinfo_mobile
func GetUserinfoRowListByMobile(MobileIsDesc bool, PageIndex, PageSize int) (userinfos []Userinfo, err error) {
	sqlstr := golibs.NewStringBuilder()
	sqlstr.Append("select UserId, UserNick, Password, Slat, Email, Mobile, LastLoginIP, Status, LoginTime from userinfo order by")
	sqlstr.Append(" Mobile")
	if MobileIsDesc {
		sqlstr.Append(" Desc")
	}
	sqlstr.Append(" limit ?,?")
	rows, err := Ha666DBConn.Query(sqlstr.ToString(), (PageIndex-1)*PageSize, PageSize)
	sqlstr.Append(",")
	if err != nil {
		return userinfos, err
	}
	if len(rows) <= 0 {
		return userinfos, nil
	}
	return _UserinfoRowsToArray(rows)
}

func _UserinfoRowsToArray(maps []map[string][]byte) ([]Userinfo, error) {
	models := make([]Userinfo, len(maps))
	var err error
	for index, obj := range maps {
		model := Userinfo{}
		model.UserId, err = strconv.ParseInt(string(obj["UserId"]), 10, 64)
		if err != nil {
			return nil, errors.New("parse UserId error: " + err.Error())
		}
		model.UserNick = string(obj["UserNick"])
		model.Password = string(obj["Password"])
		model.Slat = string(obj["Slat"])
		model.Email = string(obj["Email"])
		model.Mobile, err = strconv.ParseInt(string(obj["Mobile"]), 10, 64)
		if err != nil {
			return nil, errors.New("parse Mobile error: " + err.Error())
		}
		model.LastLoginIP = string(obj["LastLoginIP"])
		model.Status, err = strconv.Atoi(string(obj["Status"]))
		if err != nil {
			return nil, errors.New("parse Status error: " + err.Error())
		}
		model.LoginTime, err = strconv.ParseInt(string(obj["LoginTime"]), 10, 64)
		if err != nil {
			return nil, errors.New("parse LoginTime error: " + err.Error())
		}
		models[index] = model
	}
	return models, err
}
